package com.dahua.messagesyncsh.service.Impl;

import com.alibaba.fastjson2.JSON;
import com.dahua.messagesyncsh.common.Constants;
import com.dahua.messagesyncsh.config.redis.RedisUtil;
import com.dahua.messagesyncsh.criteria.FaultInfoQueryCriteria;
import com.dahua.messagesyncsh.entity.FaultInfo;
import com.dahua.messagesyncsh.mapper.FaultInfoMapper;
import com.dahua.messagesyncsh.service.FaultInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

@Slf4j
@Service
public class FaultInfoServiceImpl implements FaultInfoService {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private FaultInfoMapper faultInfoMapper;

    /*  唯一标识符用于查询单个返回，all用于查询全部返回，其余字段查询则直接sql查询*/
    @Override
    public List<FaultInfo> enquire(FaultInfoQueryCriteria criteria) {

        if(criteria.getDia_Rlt() != null){
            Object hash = redisUtil.getHash(Constants.FAULT_INFO, criteria.getDia_Rlt());

            if (hash != null){
                if (hash.equals(Constants.NULL)){
                    return Collections.emptyList();
                }
                return Collections.singletonList(JSON.parseObject(JSON.toJSONString(hash), FaultInfo.class));
            }

            List<FaultInfo> enquire = faultInfoMapper.enquire(criteria);
            if (enquire != null && !enquire.isEmpty()){
                redisUtil.setHash(Constants.FAULT_INFO, criteria.getDia_Rlt(), enquire.get(0));
            }else{
                redisUtil.setHash(Constants.FAULT_INFO, criteria.getDia_Rlt(), Constants.NULL);
            }
            return enquire;
        }

        return faultInfoMapper.enquire(criteria);
    }
}
